//
//  ServerVC.swift
//  BonjourBothSidesOniOS
//
//  Created by LevyGG on 2019/8/23.
//  Copyright © 2019 LevyGG. All rights reserved.
//

import UIKit

class ServerVC: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var readTextField: UITextField!
    @IBOutlet weak var toSendTextField: UITextField!
    @IBOutlet weak var sendButton: UIButton!
    
    private var bonjourServer: BonjourServer!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "Server"
        bonjourServer = BonjourServer()
        bonjourServer.delegate = self
        self.hideKeyboardWhenTappedAround()

    }
    
    @IBAction func sendData(_ sender: UIButton) {
        if self.toSendTextField.text != nil {
            if let data = toSendTextField.text!.data(using: String.Encoding.utf8) {
                bonjourServer.send(data)
            }
        }
    }
    


    
}

// MARK: Bonjour server delegates
extension ServerVC:BonjourServerDelegate {
    func didChangeServices() {
        tableView.reloadData()
    }
    
    func connected() {
        
    }
    
    func disconnected() {
        
    }
    
    func handleBody(_ body: NSString?) {
        guard let body = body else { return }
        readTextField.text = body as String
    }
}


extension ServerVC:UITableViewDataSource,UITableViewDelegate {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return bonjourServer.devices.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell.init(style: .value1, reuseIdentifier: "xxxxxx")
        
        var nameOfDevice = "name"
        var typeOfDevice = "type"
        
        let device = bonjourServer.devices[indexPath.row]
        nameOfDevice = device.name
        typeOfDevice = device.type
        cell.textLabel?.text = nameOfDevice
        cell.detailTextLabel?.text = typeOfDevice
        return cell

    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("Conect to: \(bonjourServer.devices[indexPath.row].name)")
        if !bonjourServer.devices.isEmpty {
            let service = bonjourServer.devices[indexPath.row]
            bonjourServer.connectTo(service)
        }
    }
}
